<template>
  <div>
    <el-upload
      :limit="1"
      action="#"
      :on-preview="preview"
      :on-remove="handleRemove"
      :on-change="changeFile"
      :before-upload="beforeUpload"
      :http-request="upload"
      :file-list="fileList"
      list-type="picture-card"
      :class="{ disabled : fileComputed }"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <!-- 进度条 -->
    <el-progress
      v-if="showPercent"
      :percentage="percent"
      style="width:180px"
    />
    <!-- /进度条 -->
    <el-dialog
      :visible.sync="showDialog"
      title="图片预览"
    >
      <img :src="imgUrl" width="100%">
    </el-dialog>

  </div>

</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDAD5i7IFySijV3MSKxMXUCfwylJdiY8Ub',
  SecretKey: 'xgAPPAfvwiHn9G9oIiwxkLjurZ3KODoA'
})
export default {
  // 组件名称
  name: 'ImageUpload',
  // 局部注册的组件
  components: {},
  // 组件参数 接收来自父组件的数据
  props: {},
  // 组件状态值
  data() {
    return {
      fileList: [], // 上传文件列表
      showDialog: false,
      imgUrl: '',
      currentFileUid: null, // 记录当前上传的uid
      showPercent: false,
      percent: 0
    }
  },
  // 计算属性
  computed: {
    fileComputed() {
      return this.fileList.length === 1
    }
  },
  // 侦听器
  watch: {},
  // 生命周期钩子   注：没用到的钩子请自行删除
  /**
  * 组件实例创建完成，属性已绑定，但DOM还未生成，el属性还不存在
  */
  created() {},
  /**
  * el 被新创建的 vm.el 替换，并挂载到实例上去之后调用该钩子。
  * 如果 root 实例挂载了一个文档内元素，当 mounted 被调用时 vm.el 也在文档内。
  */
  mounted() {},
  // 组件方法
  methods: {
    preview(file) { // 点击图片+号触发事件
      this.imgUrl = file.url
      this.showDialog = true
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
      // this.fileList = this.fileList.filter(item => item.uid !== file.uid)
    },
    changeFile(file, fileList) {
      // if (!this.fileList.some(item => item.uid === file.uid)) {
      //   this.fileList.push(file)
      // }
      // console.log(fileList.length)
      this.fileList = fileList.map(item => item)
    },
    beforeUpload(file) {
      // 检查图片格式
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.some(item => item === file.type)) {
        this.$message.error('上传图片只能是 JPG、GIF、BMP、PNG 格式!')
        return false
      }
      // 检查图片大小
      const maxSize = 5 * 1024 * 1024
      if (file.size > maxSize) {
        this.$message.error('图片只支持5MB大小')
        return false
      }
      this.currentFileUid = file.uid
      this.showPercent = true
      return true
    },
    upload(params) {
      if (params.file) {
        cos.putObject({
          Bucket: 'wawa-1308617705',
          Region: 'ap-beijing',
          Key: params.file.name,
          StorageClass: 'STANDARD',
          Body: params.file,
          onProgress: (params) => {
            this.percent = params.percent * 100
          }
        }, (err, data) => {
          // console.log(err || data)
          if (!err && data.statusCode === 200) {
            this.fileList = this.fileList.map(item => {
              if (item.uid === this.currentFileUid) {
                return { url: 'http://' + data.Location, upload: true }
              }
              return item
            })
            this.showPercent = false
            this.percent = 0
          }
        })
      }
    }
  }
}
</script>

<style>
  .disabled .el-upload--picture-card{
    display: none;
  }
</style>
